import { createRouter, createWebHashHistory, createWebHistory } from 'vue-router'
import { defineAsyncComponent } from 'vue'
import layout from '@/layout/index.vue'
import { getLocal } from '../utils/storage'
import { getPermissionListMenu } from '../api/user.js'
import { generateRoute } from '../utils/common'
import store from '@/store'
const routes = [
    {
        path: '/login',
        name: 'login',
        meta: {
            title: '登录'
        },
        component: () => import('@/view/login/index.vue'),
    },
    {
        path: '/404',
        name: '404',
        meta: {
            title: '404'
        },
        component: () => import('@/view/publicPage/404.vue'),
    },
    {
        path: '/',
        name: 'layout',
        meta: {
            title: '首页'
        },
        // alwaysShow:true,
        redirect: 'home',
        component: layout,
        children: [
            {
                path: 'home',
                name: 'home',
                meta: {
                    title: '控制台'
                },
                component: () => import('@/view/home/index.vue')
            },
        
        ]

    }
]

const router = createRouter({
    history: createWebHistory(),
    routes,
})
//导航守卫
 router.beforeEach((to, from, next) => {   
    if (checkPermission(to.path)) {
        document.title = to.meta.title
        next()
    } else {
        store.dispatch('rolesVerifyFun')
        if(store.state.rolesVerifyToken){
            next('/404')
        }else{
        window.location.href="/login"
        }
        
    }
})



async function loadAsyncRoutes() {
    let token = getLocal('token') || {}
    if (token) {
        try {
            const data = await getPermissionListMenu()
            let routers = await generateRoute(data)
            routers.map(route => {
                let url = `./../view/${route.component}.vue`
                route.component =() => import( /* @vite-ignore */`${url}`) ; 
                router.addRoute('layout', route)
            })
        } catch (error) {

        }

    }
}

await loadAsyncRoutes()

//判断当前地址是否可以访问
function checkPermission(path) {
    let hasPermission = router.getRoutes().filter(route => route.path == path).length
    if (hasPermission) {
        return true
    } else {
        return false
    }
}



export default router